package com.itheima.reggie_auto.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie_auto.common.R;
import com.itheima.reggie_auto.util.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
// @Component
public class LoginIntercceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否登录，登录则放行，不登录则不放行
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) {
            //已登录，放行
            log.info("用户已登录，用户id为：{}",empId);
            //将Id保存到线程局部变量中
            BaseContext.setCurrentId(empId);
            return true;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
